package com.tongcao.cn.processor;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.google.common.collect.Maps;
import com.tongcao.cn.constants.ProcessEnum;
import com.tongcao.cn.util.UrlSplitUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import org.thymeleaf.util.MapUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @Author:tongcao
 * @Date:2018/12/28 16:53
 * Description:
 */
@Component
public class ProcessDispatcher implements InitializingBean {


    @Resource
    BeanHelper beanHelper;

    protected Map<String, IProcess> processMap = Maps.newConcurrentMap();

    @Override
    public void afterPropertiesSet() throws Exception {
        List<IProcess> processList = beanHelper.getBeanList(IProcess.class);
        if (CollectionUtils.isNotEmpty(processList)) {
            for (IProcess process : processList) {
                processMap.put(process.routeType(), process);
            }
        }
        if (MapUtils.isEmpty(processMap)) {
            throw new IllegalArgumentException("至少设置一个process");
        }
    }

    /**
     * 路由
     *
     * @param redirectUrl
     * @return
     */
    public String route(String redirectUrl) {
        String router = UrlSplitUtil.urlSplit(redirectUrl).get("router");
        if (StringUtils.isNotBlank(router)) {
            //页面拆分
            for (ProcessEnum processEnum : ProcessEnum.values()) {
                if (StringUtils.equals(router, processEnum.getKey())) {
                    redirectUrl = processMap.get(processEnum.getKey()).process(redirectUrl);
                    return redirectUrl;
                }
            }
        }
        return redirectUrl;
    }
}
